import biApi from '@/config/server/api/bi'
import chartsOption from '@/biz/buildingHome/charOption'
import dt from '@dt/dt'
let Alldata = null
let data = null
let xUnit = ''
let xData = []
let barLineData = []
let pieData = []
let ChartApi = [
  {
    barApi: biApi.daily.chart.pkDateChart,
    pieApi: biApi.daily.chart.pkDateChartPie
  },
  {
    barApi: biApi.daily.chart.customerChart,
    pieApi: biApi.daily.chart.customerChartPie
  },
  {
    barApi: biApi.daily.chart.channelChart,
    pieApi: biApi.daily.chart.channelChartPie
  },
  {
    barApi: biApi.daily.chart.orderChart,
    pieApi: biApi.daily.chart.orderChartPie
  }
]

function downloadBase64(originURL, name) {
  const a = document.createElement('a')
  a.href = originURL
  a.download = name
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

function chartsToBase64(canvas, backgroundColor = '#fff') {
  return new Promise((resolve, reject) => {
    let w = canvas.width
    let h = canvas.height
    let context = canvas.getContext('2d')
    let data, compositeOperation, imageData
    if (backgroundColor) {
      data = context.getImageData(0, 0, w, h)
      compositeOperation = context.globalCompositeOperation
      context.globalCompositeOperation = 'destination-over'
      context.fillStyle = backgroundColor
      context.fillRect(0, 0, w, h)
    }
    imageData = canvas.toDataURL('image/png')
    if (backgroundColor) {
      context.clearRect(0, 0, w, h)
      context.putImageData(data, 0, 0)
      //globalCompositeOperation属性设置为destination-over. 然后将会在当前图形之下绘制新的图形
      context.globalCompositeOperation = compositeOperation
    }
    return resolve(imageData)
  })
}

//获取饼图bottom文字
function getBottomText(params) {
  let topText = ''
  //PK统计
  if (params.chartsType == 1) {
    if (params.TabVal == 1) {
      topText = '总线索'
    } else if (params.TabVal == 2) {
      topText = '总来人'
    } else {
      topText = '总成交'
    }
  }
  //客户统计
  if (params.chartsType == 2) {
    if (params.TabVal == 1) {
      topText = '总线索'
    } else {
      topText = '总来人'
    }
  }
  //渠道统计
  if (params.chartsType == 3) {
    if (params.TabVal == 1) {
      topText = '总线索'
    } else if (params.TabVal == 2) {
      topText = '总首访'
    } else if (params.TabVal == 3) {
      topText = '总复访'
    } else if (params.TabVal == 4) {
      topText = '总认购'
    } else if (params.TabVal == 5) {
      topText = '总签约'
    } else {
      topText = ''
    }
  }
  return topText
}
//获取饼图top总数
function getTopText(params, data) {
  let total = 0
  /*============
   * 客户统计需根据customerIds去重
   */
  if (params.chartsType == 2) {
    if (data.length == 1) {
      total = data[0].value
    } else {
      if (data[0].customerIds && data[1].customerIds) {
        let arr = [...new Set([...data[0]?.customerIds, ...data[1]?.customerIds])]
        return arr.length
      } else {
        return 0
      }
    }
  } else {
    if (data.length == 1) {
      total = data[0].value
    } else {
      data.forEach((item) => {
        total += Number(item.value)
      })
    }
  }
  return total
}

function getBarLineData(params) {
  console.log(ChartApi[2].barApi, params.chartsType, '@@@@')
  let data = {
    endTime: params.checkTime.endTime, //结束时间
    level: 4, //组织级别：1事业部、2分公司、3事业处、4案场
    orgId: dt.buildInfo().housesId, //组织ID
    queryType: params.TabVal, //查询类型 tab值
    startTime: params.checkTime.startTime //开始时间
  }
  return ChartApi[Number(params.chartsType) - 1].barApi
    .fetch(data)
    .then((res) => {
      console.log(res, '柱状图')
      if (res.data) {
        return res.data
      } else {
        return { series: [], xAxis: { value: [] } }
      }
    })
    .catch(() => {
      return []
    })
}

function getPieData(params) {
  let data = {
    endTime: params.checkTime.endTime, //结束时间
    level: 4, //组织级别：1事业部、2分公司、3事业处、4案场
    orgId: dt.buildInfo().housesId, //组织ID
    queryType: params.TabVal, //查询类型 tab值
    startTime: params.checkTime.startTime //开始时间
  }
  return ChartApi[Number(params.chartsType) - 1].pieApi
    .fetch(data)
    .then((res) => {
      console.log(res, '饼图')
      if (res.data) {
        return res.data
      } else {
        return []
      }
    })
    .catch(() => {
      return []
    })
}
//获取数据 并处理数据
function getData(params) {
  if (params.page_type == 'list') {
    return getBarLineData(params).then((res) => {
      barLineData = res.series || []
      xData = res.xAxis ? res.xAxis.value : []
      xUnit = res.xAxis ? res.xAxis.name : ''
      barLineData.forEach((item) => {
        item.data = item.value
        item.type = params.type == 'optionBar' ? 'bar' : 'line'
      })
      Alldata = { barLineData, pieData, xData, xUnit }
      return Alldata
    })
  } else {
    if (params.flag && barLineData.length && xData.length && pieData.length) {
      return new Promise((resolve) => {
        barLineData.forEach((item) => {
          item.data = item.value
          item.type = params.type == 'optionBar' ? 'bar' : 'line'
        })
        Alldata = { barLineData, pieData, xData, xUnit }
        return resolve(Alldata)
      })
    } else {
      return Promise.all([getBarLineData(params), getPieData(params)]).then((res) => {
        barLineData = res[0].series
        xData = res[0].xAxis.value
        xUnit = res[0].xAxis ? res[0].xAxis.name : ''
        pieData = res[1]
        barLineData.forEach((item) => {
          item.data = item.value
          item.type = params.type == 'optionBar' ? 'bar' : 'line'
        })
        Alldata = { barLineData, pieData, xData, xUnit }
        return Alldata
      })
    }
  }
}
/*
 *  type, //图标模式 （柱状图 折线图 饼图）
 *  checkTime: // 请求日期
 *  chartsType // 统计项 （PK数据 客户统计 渠道统计 销售统计）
 *  filterData // 指标筛选项
 *  TabVal:    // tab切换
 *  unit       // Y轴单位
 *  topText    // 饼状图 中间上 文字
 *  bottomText // 饼状图 中间下 文字
 * */
function getInfoData(params) {
  console.log(params, 'params****')
  let option = null
  return getData(params).then((res) => {
    console.log(res, 'res*****')
    let data = {},
      filterList = []
    //获取所有的指标筛选项 注：在chartsType==1 && chartsType==3（pk数据\渠道统计）时 取接口返回得数据作为筛选指标
    if (params.chartsType && (params.chartsType == 1 || params.chartsType == 3)) {
      res.pieData.forEach((item) => {
        filterList.push({ name: item.name, configType: item.configType })
      })
    }

    if (params.filterData && params.filterData.length > 0) {
      data.barLineData = res.barLineData.filter((item) => params.filterData.some((i) => i === item.name))
      data.pieData = res.pieData.filter((item) => params.filterData.some((i) => i === item.name))
    } else {
      data.barLineData = res.barLineData.length > 5 ? res.barLineData.slice(0, 5) : res.barLineData
      data.pieData = res.pieData.length > 5 ? res.pieData.slice(0, 5) : res.pieData
    }
    if (params.type == 'optionBar') {
      let opt = {
        series: data.barLineData,
        xData: res.xData,
        unit: params.unit,
        xUnit: res.xUnit
      }
      option = chartsOption.optionBar(opt)
    }
    if (params.type == 'optionLine') {
      let opt = {
        series: data.barLineData,
        xData: res.xData,
        unit: params.unit,
        xUnit: res.xUnit
      }
      option = chartsOption.optionLine(opt)
    }
    if (params.type == 'optionPie') {
      let opt = {
        series: data.pieData,
        unit: params.unit,
        topText: getTopText(params, data.pieData),
        bottomText: getBottomText(params)
      }
      option = chartsOption.optionPie(opt)
    }
    return { option, filterList }
  })
}

function noDataTxt(type) {
  let text = ''
  if (type == 1) {
    text = `
    本周暂无“PK数据”，您可在“编辑日报”界面中，
    点击右上角“添加联代”或“添加竞品”按钮进行维护。`
  } else {
    text = `
    该模块已被设置为隐藏，您可在“编辑日报”界面中，
        点击右上角“设置日报模板”按钮重新打开。`
  }
  return text
}
export default {
  downloadBase64,
  chartsToBase64,
  getInfoData,
  noDataTxt
}
